<template>
  <div class="app-container" v-loading="loading">
    <!-- <limit v-model="form" /> -->

    <bothParties v-model="form" ref="bothParties" state='write' />
    <!-- 担保人 -->
    <surety v-model="form" ref="surety" state='write' />
    <!--  买受人 -->
    <vendee v-model="form" ref="vendee" state='write' v-if="($route.query.rentType==2 || $route.query.rentType==4)" />
    <vehicle v-model="form" ref="vehicle" state='write' />
    <other v-model="form" ref="other" state='write' />
    <contract v-model="form" ref="contract" state='write' />
    <cartMessage v-model="form" ref="cartMessage" state='write' />
    <div style="text-align: right;margin-top: 50px;background-color: #fff;height: 60px;line-height: 60px;box-sizing: border-box;padding-right: 20px;">
      <el-button @click="cancel">取消</el-button>
      <el-button @click="save" type="primary" plain v-hasPermi="['placeOrder:placeOrderAdd:save']">保存</el-button>
      <el-button @click="submit" type="primary" v-hasPermi="['placeOrder:placeOrderAdd:submit']">提交</el-button>
    </div>

  </div>
</template>
<script>
import limit from "./components/limit";
import bothParties from "./components/bothParties";
import surety from "./components/surety";
import vendee from "./components/vendee";
import vehicle from "./components/vehicle";
import other from "./components/other";
import contract from "./components/contract";
import cartMessage from "./components/cartMessage";
import {
  orderDraftSave,
  orderSubmit,
  getOrderDetail,
  getRule,
  orderPre
} from "@/api/vehicleOrder";
export default {
  name: "PlaceOrderAdd",
  components: {
    bothParties,
    surety,
    vendee,
    vehicle,
    other,
    contract,
    cartMessage,
    limit
  },
  data() {
    return {
      loading: false,
      form: {
        supplementDriverList: [],
        supplementSuretyPersonalList: [], //担保人个人
        supplementSuretyCorporateList: [], //担保人企业
        supplementOther: { overRange: '', offSite: '' }, //其他信息
        supplementEmptor: {}, //买受人信息
        supplementContract: { dailyRentBeforeDelivery: '/', paymentScheduleList: [], tenancyCalcInclusiveReplacementKey: '2', limitInvoicingDaysKey: '2', restrictedPaymentDayKey: '2', includesRentPaymentScheduleKey: '2' }, //合同信息
        supplementDelivery: { deliveryType: "2", point: [], dropOffPoint: [], returnTheCar: [] }, //交车信息
        orderPlanList: [], //车型车辆明细
        dataListTable: [],
        contractTime: []
      },
    };
  },
  mounted() {
    if (this.$route.query.beFrom == "OrderView") {
      console.log("编辑");
      this.getOrderDetail();
    } else {
      console.log("下单新增");
      this.getRule()
    }
  },
  methods: {
    async orderPre() {
      try {
        let res = await orderPre(this.$route.query.preOrderId)
        this.$set(
          this.form,
          "lessorIdCopy",
          res.data.lessorId
        );
        this.$set(
          this.form,
          "leaseeIdCopy",
          res.data.leaseeId
        );
      } catch (error) { }
    },
    async getRule() {
      try {
        let res = await getRule(this.$route.query.leaseContractTemplateId)
        this.$set(
          this.form.supplementOther,
          "overrangePrice",
          res.data.overmileageFeeParam
        );
        this.$set(
          this.form.supplementOther,
          "overRange",
          res.data.overmileageFeeParam
        );
        this.$set(
          this.form.supplementDelivery,
          "offSiteReturnPrice",
          res.data.offsiteParam
        );
        this.$set(
          this.form.supplementDelivery,
          "offSite",
          res.data.offsiteParam
        );
      } catch (error) {
        console.log(error, 'error');
      }
    },
    valid() {
      return new Promise(async (resolve) => {
        let result = true;
        let refs = Object.values(this.$refs);
        for (let index = 0; index < refs?.length; index++) {
          const ref = refs[index];
          if (Object.prototype.toString.call(ref) == "[object Array]") {
            for (let i = 0; i < ref.length; i++) {
              const element = ref[i];
              if (element?.valid) {
                let rc = await element?.valid?.();
                result = result && rc;
              }
              if (element?.validate) {
                let rf = await this._valid(ref);
                result = result && rf;
              }
              if (element?.form_validate) {
                let rf = await this._valid(ref, "form_validate");
                result = result && rf;
              }
            }
          } else {
            if (ref?.valid) {
              let rc = await ref?.valid?.();
              result = result && rc;
            }
            if (ref?.validate) {
              let rf = await this._valid(ref);
              result = result && rf;
            }
            if (ref?.form_validate) {
              let rf = await this._valid(ref, "form_validate");
              result = result && rf;
            }
          }
        }
        resolve(result);
      });
    },
    async getOrderDetail() {
      this.loading = true;
      try {
        let res = await getOrderDetail(this.$route.query.orderId);
        this.form = res.data;
        this.$set(
          this.form,
          "contactPersonId",
          res.data.contactPersonId
        );
        this.$set(
          this.form.supplementDelivery,
          "address",
          res.data.supplementDelivery.deliveryAddr
        );
        if (res.data.estimatedDeliveryTime === '1000-01-01') {
          this.$set(
            this.form.supplementDelivery,
            "estimatedDeliveryTime",
            undefined
          );
        } else {
          this.$set(
            this.form.supplementDelivery,
            "estimatedDeliveryTime",
            res.data.estimatedDeliveryTime
          );
        }
        this.form.dataListTable = res.data.orderPlanList;
        this.form.supplementDelivery.point = [
          res.data.supplementDelivery.deliveryProvinceId,
          res.data.supplementDelivery.deliveryCityId,
          res.data.supplementDelivery.deliveryAreaId,
        ];
        this.form.supplementDelivery.dropOffPoint = [
          res.data.supplementDelivery.deliveryProvinceId,
          res.data.supplementDelivery.deliveryCityId,
          res.data.supplementDelivery.deliveryAreaId,
        ];
        this.form.supplementDelivery.returnTheCar = [
          res.data.supplementDelivery.returnProvinceId,
          res.data.supplementDelivery.returnCityId,
          res.data.supplementDelivery.returnAreaId,
        ];
        if (this.form.supplementSuretyPersonalList == null) {
          this.form.supplementSuretyPersonalList = []
        }
        if (this.form.supplementSuretyCorporateList == null) {
          this.form.supplementSuretyCorporateList = []
        }
        if (res.data.supplementContract.timeStart == '1000-01-01' && res.data.supplementContract.timeFinish == '1000-01-01') {
          this.$set(
            this.form.supplementContract,
            "timeStart",
            undefined
          );
          this.$set(
            this.form.supplementContract,
            "timeFinish",
            undefined
          );
        }
        if (!res.data.supplementOther.overrangePrice || !res.data.supplementDelivery.offSiteReturnPrice) {
          this.getRule()
        } else {
          this.$set(
            this.form.supplementOther,
            "overRange",
            res.data.supplementOther.overrangePrice
          );
          this.$set(
            this.form.supplementDelivery,
            "offSite",
            res.data.supplementDelivery.offSiteReturnPrice
          );
        }
        if (this.form.businessPersonId == null) { this.form.businessPersonId = undefined }
        if (this.form.lessorId == null || this.form.leaseeId == null) {
          this.orderPre()
          this.form.lessorId = undefined
          this.form.leaseeId = undefined
        }
        if (this.form.invoiceType == '') { this.form.invoiceType = undefined }
        if (this.form.contactPersonId == null || this.form.contactPersonId == '') { this.form.contactPersonId = undefined }
        if (this.form.supplementEmptor.buyerId == null) {
          this.$set(
            this.form.supplementEmptor,
            "buyerId",
            undefined
          );
        }
        this.loading = false;
      } catch (error) {
        this.loading = false;
      }
    },
    async submit() {
      let result = await this.valid();
      console.log(result, "result");
      if (result) {
        const loading = this.$loading({
          lock: true,
          text: "提交中",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        this.data();
        orderSubmit(this.form)
          .then((res) => {
            if (res.code === 200) {
              loading.close();
              this.$message.success("提交成功");
              this.cancel()
            }
          })
          .catch(() => {
            loading.close();
          });
      } else {
        this.error();
      }
    },
    save() {
      const loading = this.$loading({
        lock: true,
        text: "保存中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.data();
      orderDraftSave(this.form)
        .then((res) => {
          if (res.code === 200) {
            loading.close();
            this.$message.success("保存成功");
            this.cancel()
          }
        })
        .catch(() => {
          loading.close();
        });
    },
    error() {
      this.$nextTick(() => {
        const el = document.querySelectorAll(".el-form-item__error")[0];
        el.scrollIntoView({ block: "center", behavior: "smooth" });
      });
    },
    data() {
      this.$route.query.beFrom !== "OrderView"
        ? (this.form = {
          ...this.form,
          estimatedDeliveryTime:
            this.form.supplementDelivery.estimatedDeliveryTime,
          businessPersonName: this.$refs?.bothParties?.businessList
            .filter((v) => {
              if (v.userId == this.form.businessPersonId) {
                return v;
              }
            })
            .filter((i) => i)[0]?.userName,
          lessorName: this.$refs?.bothParties?.rentOutList
            .filter((v) => {
              if (v.deptId == this.form.lessorId) {
                return v;
              }
            })
            .filter((i) => i)[0]?.deptName,
          leaseeName: this.$refs?.bothParties?.CustomerList.filter((v) => {
            if (v.customerId == this.form.leaseeId) {
              return v;
            }
          }).filter((i) => i)[0]?.customerName,
          contactPersonName: this.$refs?.bothParties?.customerListIphone
            .filter((v) => {
              if (v.contactId == this.form.contactPersonId) {
                return v;
              }
            })
            .filter((i) => i)[0]?.contactName,
          supplementSuretyPersonalList: this.form.supplementSuretyPersonalList
            .map((v) => {
              return {
                ...v,
                // suretyType: 1,
              };
            })
            .filter((i) => i),
          supplementSuretyCorporateList:
            this.form.supplementSuretyCorporateList
              .map((v) => {
                return {
                  ...v,
                  // suretyType: 2,
                };
              })
              .filter((i) => i),
          contactMobile: this.$refs.bothParties.contactMobile,
          preOrderId: this.$route.query.preOrderId,
          supplementContract: {
            ...this.form.supplementContract,
            paymentScheduleTotalRent: this.$refs.contract.totalPrice,
            quantityDelivered: this.$refs.contract.bothSides,
          },
          supplementDelivery: {
            ...this.form.supplementDelivery,
            deliveryProvinceId:
              this.form.supplementDelivery?.deliveryType == 2
                ? this.form.supplementDelivery?.point[0]
                : this.form.supplementDelivery?.dropOffPoint[0],
            deliveryCityId:
              this.form.supplementDelivery?.deliveryType == 2
                ? this.form.supplementDelivery?.point[1]
                : this.form.supplementDelivery?.dropOffPoint[1],
            deliveryAreaId:
              this.form.supplementDelivery?.deliveryType == 2
                ? this.form.supplementDelivery?.point[2]
                : this.form.supplementDelivery?.dropOffPoint[2],
            returnProvinceId:
              this.form.supplementDelivery?.deliveryType == 2
                ? this.form.supplementDelivery?.point[0]
                : this.form.supplementDelivery?.returnTheCar[0],
            returnCityId:
              this.form.supplementDelivery.deliveryType == 2
                ? this.form.supplementDelivery?.point[1]
                : this.form.supplementDelivery?.returnTheCar[1],
            returnAreaId:
              this.form.supplementDelivery.deliveryType == 2
                ? this.form.supplementDelivery?.point[2]
                : this.form.supplementDelivery?.returnTheCar[2],
            deliveryAddr:
              this.form.supplementDelivery.deliveryType == 2
                ? this.form.supplementDelivery?.address
                : this.form.supplementDelivery?.deliveryAddr,
            returnAddr:
              this.form.supplementDelivery.deliveryType == 2
                ? this.form.supplementDelivery?.address
                : this.form.supplementDelivery?.returnAddr,
          },
        })
        : (this.form = {
          ...this.form,
          estimatedDeliveryTime:
            this.form.supplementDelivery.estimatedDeliveryTime,
          businessPersonName: this.$refs?.bothParties?.businessList
            .filter((v) => {
              if (v.userId == this.form.businessPersonId) {
                return v;
              }
            })
            .filter((i) => i)[0]?.userName,
          lessorName: this.$refs?.bothParties?.rentOutList
            .filter((v) => {
              if (v.deptId == this.form.lessorId) {
                return v;
              }
            })
            .filter((i) => i)[0]?.deptName,
          leaseeName: this.$refs?.bothParties?.CustomerList.filter((v) => {
            if (v.customerId == this.form.leaseeId) {
              return v;
            }
          }).filter((i) => i)[0]?.customerName,
          contactPersonName: this.$refs?.bothParties?.customerListIphone
            .filter((v) => {
              if (v.contactId == this.form.contactPersonId) {
                return v;
              }
            })
            .filter((i) => i)[0]?.contactName,
          contactMobile: this.$refs.bothParties.contactMobile,
          supplementContract: {
            ...this.form.supplementContract,
            paymentScheduleTotalRent: this.$refs.contract.totalPrice,
            quantityDelivered: this.$refs.contract.bothSides,
          },
          supplementDelivery: {
            ...this.form.supplementDelivery,
            deliveryProvinceId:
              this.form.supplementDelivery?.deliveryType == 2
                ? this.form.supplementDelivery?.point[0]
                : this.form.supplementDelivery?.dropOffPoint[0],
            deliveryCityId:
              this.form.supplementDelivery?.deliveryType == 2
                ? this.form.supplementDelivery?.point[1]
                : this.form.supplementDelivery?.dropOffPoint[1],
            deliveryAreaId:
              this.form.supplementDelivery?.deliveryType == 2
                ? this.form.supplementDelivery?.point[2]
                : this.form.supplementDelivery?.dropOffPoint[2],
            returnProvinceId:
              this.form.supplementDelivery?.deliveryType == 2
                ? this.form.supplementDelivery?.point[0]
                : this.form.supplementDelivery?.returnTheCar[0],
            returnCityId:
              this.form.supplementDelivery.deliveryType == 2
                ? this.form.supplementDelivery?.point[1]
                : this.form.supplementDelivery?.returnTheCar[1],
            returnAreaId:
              this.form.supplementDelivery.deliveryType == 2
                ? this.form.supplementDelivery?.point[2]
                : this.form.supplementDelivery?.returnTheCar[2],
            deliveryAddr:
              this.form.supplementDelivery.deliveryType == 2
                ? this.form.supplementDelivery?.address
                : this.form.supplementDelivery?.deliveryAddr,
            returnAddr:
              this.form.supplementDelivery.deliveryType == 2
                ? this.form.supplementDelivery?.address
                : this.form.supplementDelivery?.returnAddr,
          },
        });
    },
    cancel() {
      this.$tab.closeOpenPage(this.$route);
      if (this.$route.query.beFrom == 'PlaceOrderView') {
        this._toPage({
          name: this.$route.query.beFrom,
        });
      } else if (this.$route.query.isMenu) {
        this._toPage({
          name: this.$route.query.beFrom,
          query: {
            preOrderId: this.$route.query.preOrderId,
          }
        });
      } else {
        this._toPage({
          name: this.$route.query.beFrom,
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  // background-color: #fff;
  box-sizing: border-box;
  padding-left: 30px;
  .box {
    width: 100%;
    .title {
      border-left: 3px solid #3280fc;
      padding-left: 5px;
      box-sizing: border-box;
    }
  }
}
</style>
